#include <tsin/library/BulletDieOutEvent.hpp>

#include <tsin/runtime/GameRuntime.hpp>
#include <tsin/runtime/BulletRuntime.hpp>

#include <tsin/library/GameViewport.hpp>

#include <cstring>
#define _USE_MATH_DEFINES
#include <cmath>

using namespace tsin;

BulletDieOutEvent::BulletDieOutEvent(bool d)
        : BulletEvent(d), glacis(0.0f)
{
}

DynamicObject *BulletDieOutEvent::copy()
{
        return DynamicObject::copy(new BulletDieOutEvent(true));
}

void BulletDieOutEvent::init(float glacis)
{
        this->glacis = glacis;
}

void BulletDieOutEvent::reinit()
{
        float arg1 = arguments[0]->getFloat();

        switch(nrArguments) {
        case 0:
                init();
                break;
        case 1:
                if (strcmp(desp, "N") == 0)
                        init(arg1);
                break;
        }
}

bool BulletDieOutEvent::trigger(BulletRuntime &bullet, void *)
{
        return bullet.stage == BULLET_STAGE_LIVE;
}

BulletEvent *BulletDieOutEvent::handle(BulletRuntime &bullet, void *)
{
        float borderX = bullet.residence->width()/2 + bullet.w/2 + glacis;
        float borderY = bullet.residence->height()/2 + bullet.h/2 + glacis;

        if (bullet.x < -borderX || bullet.x > borderX ||
            bullet.y < -borderY || bullet.y > borderY) {
                bullet.stage = BULLET_STAGE_DIED;
                return next();
        }
        return this;
}

DynamicObject *bindDieOutEvent()
{
        return new BulletDieOutEvent(true);
}
